import 'package:douhuaxiangsu/page/palette_setting.dart';
import 'package:flutter/material.dart';

import '../entity/palette_model.dart';
import '../services/palette_service.dart';

class PaletteSettingListPage extends StatefulWidget {
  const PaletteSettingListPage({super.key});

  @override
  State<PaletteSettingListPage> createState() => _PaletteSettingListPageState();
}

class _PaletteSettingListPageState extends State<PaletteSettingListPage> {
  List<PaletteModel> paletteList = [];

  bool deleteCheck = true;

  @override
  void initState() {
    _loadPaletteConfig();
    super.initState();
  }

  _loadPaletteConfig() {
    PaletteService.queryAll().then((result) {
      setState(() {
        paletteList = result;
      });
    });
  }

  _saveAndLoadPaletteConfig(PaletteModel? paletteModel) {
    if (paletteModel != null) {
      PaletteService.saveOrUpdatePalette(
        paletteModel,
      ).then((id) => _loadPaletteConfig());
    }
  }

  @override
  Widget build(BuildContext context) {
    MediaQueryData mediaQuery = MediaQuery.of(context);
    // 包含安全区域的尺寸
    double safeWidth = mediaQuery.size.width;
    double iconSize = 25;
    int iconCount = (safeWidth / iconSize).floor() - 5;
    if (iconCount < 0) {
      iconCount = 0;
    }
    return Scaffold(
      appBar: AppBar(
        // 设置页标题
        title: const Text('配置调色板'),
        leading: IconButton(
          // 返回按钮
          icon: const Icon(Icons.arrow_back),
          // 返回到上一页
          onPressed: () => Navigator.of(context).pop(),
        ),
        // 右上角按钮区域
        actions: [
          TextButton.icon(
            icon: const Icon(Icons.add),
            label: const Text('新增调色板'),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => PaletteSettingPage(
                    paletteModel: PaletteModel.fromJson(const {}),
                  ),
                ),
              ).then((value) => _saveAndLoadPaletteConfig(value));
            },
          ),
          SizedBox(width: 10),
        ],
      ),
      body: ListView(
        children: (paletteList.isEmpty
            ? [
                ListTile(
                  title: Text('无调色板'),
                  subtitle: Text('无调色板'),
                  onTap: () {},
                ),
              ]
            : paletteList
                  .map(
                    (paletteModel) => ListTile(
                      title: Text(paletteModel.name),
                      subtitle: Row(
                        children: paletteModel.data
                            .take(iconCount)
                            .map(
                              (colorItem) => Icon(
                                colorItem.view
                                    ? Icons.square
                                    : Icons.visibility_off,
                                color: colorItem.color,
                                size: 25,
                              ),
                            )
                            .toList(),
                      ),
                      trailing: IconButton(
                        icon: Icon(Icons.delete),
                        onPressed: () {
                          final id = paletteModel.id;
                          if (id != null) {
                            if (deleteCheck) {
                              _showEditPaletteColorDialog(context, id);
                            } else {
                              PaletteService.delete(id);
                              _loadPaletteConfig();
                            }
                          }
                        },
                      ),
                      onTap: () {
                        Navigator.of(context)
                            .push(
                              MaterialPageRoute(
                                builder: (context) => PaletteSettingPage(
                                  paletteModel: paletteModel,
                                ),
                              ),
                            )
                            .then(
                              (value) => {_saveAndLoadPaletteConfig(value)},
                            );
                      },
                    ),
                  )
                  .toList()),
      ),
    );
  }

  /// 删除调色板弹窗
  void _showEditPaletteColorDialog(BuildContext context, int id) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (BuildContext context, StateSetter setState) {
            return AlertDialog(
              title: Text('删除调色板?'),
              content: SingleChildScrollView(
                child: Column(
                  children: [
                    SwitchListTile(
                      title: const Text('退出此页面前不再提醒'),
                      value: !deleteCheck,
                      onChanged: (bool value) {
                        // 更新Switch内部状态
                        setState(() {
                          deleteCheck = !value;
                        });
                      },
                    ),
                  ],
                ),
              ),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: const Text('取消'),
                ),
                TextButton(
                  onPressed: () {
                    PaletteService.delete(id);
                    Navigator.of(context).pop();
                  },
                  child: const Text('确定'),
                ),
              ],
            );
          },
        );
      },
    ).then((onValue) {
      _loadPaletteConfig();
    });
  }
}
